package com.backend.common.ai;

import com.backend.common.exception.BusinessException;
import com.backend.config.ai.DeepseekConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Deepseek API客户端
 */
@Slf4j
@Component
public class DeepseekClient {

    private final RestTemplate restTemplate;
    private final DeepseekConfig deepseekConfig;
    private final ObjectMapper objectMapper;
    
    // 备选模型列表
    private static final String[] FALLBACK_MODELS = {
        "deepseek-chat",
        "deepseek-ai/deepseek-chat-v1"
    };

    public DeepseekClient(RestTemplate restTemplate, DeepseekConfig deepseekConfig, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.deepseekConfig = deepseekConfig;
        this.objectMapper = objectMapper;
    }

    /**
     * 发送聊天请求
     *
     * @param messages      消息列表
     * @param temperature   温度值
     * @param maxTokens     最大token数
     * @param responseJsonFormat 是否要求JSON格式响应
     * @return 响应内容
     */
    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2))
    public String chatCompletion(List<ChatMessage> messages, double temperature, int maxTokens, boolean responseJsonFormat) {
        String apiUrl = deepseekConfig.getBaseUrl() + "/chat/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(deepseekConfig.getApiKey());
        
        // 尝试所有可用的模型
        Exception lastException = null;
        for (String model : FALLBACK_MODELS) {
            try {
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", model);
                requestBody.put("messages", messages);
                requestBody.put("temperature", temperature);
                requestBody.put("max_tokens", maxTokens);
                
                if (responseJsonFormat) {
                    Map<String, String> responseFormat = new HashMap<>();
                    responseFormat.put("type", "json_object");
                    requestBody.put("response_format", responseFormat);
                }
                
                String requestBodyJson = objectMapper.writeValueAsString(requestBody);
                log.info("DeepSeek API请求 (模型: {}): {}", model, requestBodyJson);
                
                HttpEntity<String> entity = new HttpEntity<>(requestBodyJson, headers);
                ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
                
                String responseBody = response.getBody();
                log.info("DeepSeek API响应 (模型: {}): {}", model, responseBody);
                
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                Map<String, Object> choicesMap = ((List<Map<String, Object>>) responseMap.get("choices")).get(0);
                Map<String, Object> messageMap = (Map<String, Object>) choicesMap.get("message");
                
                return (String) messageMap.get("content");
            } catch (Exception e) {
                lastException = e;
                log.warn("使用模型 {} 调用DeepSeek API失败: {}", model, e.getMessage());
                // 继续尝试下一个模型
            }
        }
        
        // 所有模型都失败
        log.error("所有模型调用DeepSeek API都失败", lastException);
        throw new BusinessException("AI 审核服务暂时不可用: " + lastException.getMessage());
    }

    /**
     * 调用 Deepseek API 进行文件格式审核
     * 
     * @param systemPrompt 系统提示词
     * @param userPrompt   用户提示词
     * @return 模型返回的文本
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000))
    public String formatAuditChatCompletion(String systemPrompt, String userPrompt) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(ChatMessage.builder().role("system").content(systemPrompt).build());
        messages.add(ChatMessage.builder().role("user").content(userPrompt).build());
        
        return chatCompletion(
                messages,
                deepseekConfig.getFormatAuditTemperature(),
                deepseekConfig.getFormatAuditMaxTokens(),
                true
        );
    }

    /**
     * 聊天消息
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ChatMessage {
        private String role;
        private String content;
    }
} 